<?php
namespace Home\Model;
/**
 * 提现
 */
class ApplyModel extends BaseModel {
    public function __construct(){
        parent::__construct();
        
        
    }

    

    public function userInfo(){


        $USER = session('WST_USER');


        $sql = "select u.userId,u.userMoney,(select fieldValue from oto_sys_configs where `fieldCode`='applyMin' limit 1 ) as applyMin from oto_users as u where u.userId=".$USER['userId'].' limit 1';

        $res = $this->queryRow($sql);


        return $res;
    }


    public function shopsInfo(){
        $USER = session('WST_USER');


        $sql = "select s.userId,s.bizMoney,(select fieldValue from oto_sys_configs where `fieldCode`='applyMin' limit 1 ) as applyMin from oto_shops as s where s.userId=".$USER['userId'].' limit 1';

        $res = $this->queryRow($sql);


        return $res;



    }

    public function  checkShopBalance(){
        $USER = session('WST_USER');
        //   $data=array('valid'=>false);

        $tempdata=M('shops')->where(array('userId'=>$USER['userId']))->find();

        if($tempdata['bizMoney']>I('applyPrice')){

            $data=array('valid'=>true);
        }else{
            $data=array('valid'=>false);
        }



        return $data;
    }





    public function  checkBalance(){
        $USER = session('WST_USER');
     //   $data=array('valid'=>false);

        $tempdata=M('users')->where(array('userId'=>$USER['userId']))->find();

        if($tempdata['userMoney']>I('applyPrice')){

            $data=array('valid'=>true);
        }else{
            $data=array('valid'=>false);
        }



        return $data;
    }

    public function addApplyBank($data){
        if($data['userId']&&$data['bankUserName']&&$data['bankName']&&$data['bankAccess']&&$data['bankNum']){


        $nData=array(
            'userId'=>$data['userId'],
            'bankUserName'=>$data['bankUserName'],
            'bankName'=>$data['bankName'],
            'bankAccess'=>$data['bankAccess'],
            'bankNum'=>$data['bankNum'],
            'time'=>time()

        );
            $where =array(
                'userId'=>$data['userId'],
                'bankUserName'=>$data['bankUserName'],
                'bankName'=>$data['bankName'],
                'bankAccess'=>$data['bankAccess'],
                'bankNum'=>$data['bankNum']
            );
            $re = M('apply_bank')->where($where)->find();
                if(!$re){
                    M('apply_bank')->data($nData)->add();
                }


        }
    }

    //处理提现申请
    public  function  checkApply(){
            $data=I('post.');

        $USER = session('WST_USER');
        $data['userId'] = isset($USER['userId'])?$USER['userId']:session('oto_userId');

//             $data['userId'] = $USER['userId'];
        $this->addApplyBank($data);
        $USER = M('users');

        $checkApply=M('apply')->where(array('userId'=>$data['userId'],'status'=>0,'applyType'=>0))->find();


        if($checkApply){

            $error=array(
                'status'=>false,
                'error'=>'已有申请审核中'
            );
            return $error;
        }

        $userMoney = $USER->where(array('userId'=>$data['userId']))->getField('userMoney');
        if($userMoney<$data['applyPrice']){
            $error=array(
                'status'=>false,
                'error'=>'申请金额大于余额'
            );
            return $error;
        }

        $applyMin = M('sys_configs')->where(array('fieldCode'=>'applyMin'))->getField('fieldValue');

        if($applyMin>$data['applyPrice']){

            $error=array(
                'status'=>false,
                'error'=>'申请金额不能小于最低限制'
            );
            return $error;

        }

        // if(!$this->WxCheckApplyPassword($data['userId'],I('payPwd'))){
        //     $error=array(
        //         'status'=>false,
        //         'error'=>'支付密码不正确'
        //     );
        //     return $error;
        // }



        $USER->startTrans();
        $setBalance=$USER->where(array('userId'=>$data['userId']))->setDec('userMoney',$data['applyPrice']);

        if($setBalance){
            $nData=array(
                'userId'=>$data['userId'],
                'tel'=>$data['tel'],
                'applyPrice'=>$data['applyPrice'],
                'bankUserName'=>isset($data['bankUserName'])?$data['bankUserName']:'',
                'bankName'=>isset($data['bankName'])?$data['bankName']:'',
                'bankAccess'=>isset($data['bankAccess'])?$data['bankAccess']:'',
                'bankNum'=>isset($data['bankNum'])?$data['bankNum']:'',
                'remark'=>isset($data['remark'])?$data['remark']:'',
                'time'=>time()
            );

            $status=M('apply')->data($nData)->add();

                


                
            if($status>0){
                $USER->commit();
                $userMoney = M('users')->where(array('userId'=>$data['userId']))->getField('userMoney');

                $r = $this->moneyRecord(4,$data['applyPrice'],'',0,$data['userId'],$userMoney,'买家提现申请提现',3);

            }else{

                $USER->rollback();
                $error=array(
                    'status'=>false,
                    'error'=>'增加申请记录失败'
                );
                return $error;
            }

        }else{
            $USER->rollback();
            $error=array(
                'status'=>false,
                'error'=>'申请异常'
            );
            return $error;
        }


        $re=array('status'=>true,'success'=>$status);





        return $re;
    }



    //处理提现申请
    public  function  checkShopApply(){
        $data=I('post.');
        $USER = session('WST_USER');
        $data['userId'] = isset($USER['userId'])?$USER['userId']:session('oto_userId');
        $this->addApplyBank($data);
        $SHOPS = M('shops');
//        $user=M('users')->where(array('userId'=>$data['userId']))->find();
        $checkApply=M('apply')->where(array('userId'=>$data['userId'],'status'=>0,'applyType'=>1))->find();




        if($checkApply){

            $error=array(
                'status'=>false,
                'error'=>'已有申请审核中'
            );
            return $error;
        }
        $bizMoney = $SHOPS->where(array('userId'=>$data['userId']))->getField('bizMoney');
        if($bizMoney<$data['applyPrice']){
            $error=array(
                'status'=>false,
                'error'=>'申请金额大于余额'
            );
            return $error;
        }

        $applyMin = M('sys_configs')->where(array('fieldCode'=>'applyMin'))->getField('fieldValue');

        if($applyMin>$data['applyPrice']){

            $error=array(
                'status'=>false,
                'error'=>'申请金额不能小于最低限制'
            );
            return $error;

        }



        if(!$this->WxCheckApplyPassword($data['userId'],I('payPwd'))){
            $error=array(
                'status'=>false,
                'error'=>'支付密码不正确'
            );
            return $error;
        }



        M()->startTrans();

        $setBalance=$SHOPS->where(array('userId'=>$data['userId']))->setDec('bizMoney',$data['applyPrice']);

        if($setBalance){
            $nData=array(
                'userId'=>$data['userId'],
                'tel'=>$data['tel'],
                'applyPrice'=>$data['applyPrice'],
                'applyType'=>1,
                'bankUserName'=>isset($data['bankUserName'])?$data['bankUserName']:'',
                'bankName'=>isset($data['bankName'])?$data['bankName']:'',
                'bankAccess'=>isset($data['bankAccess'])?$data['bankAccess']:'',
                'bankNum'=>isset($data['bankNum'])?$data['bankNum']:'',
                'remark'=>isset($data['remark'])?$data['remark']:'',
                'time'=>time()
            );

            $status=M('apply')->data($nData)->add();





            if($status>0){
                M()->commit();
                $userMoney = M('shops')->where(array('userId'=>$data['userId']))->getField('bizMoney');

                $r = $this->moneyRecord(7,$data['applyPrice'],'',0,$data['userId'],$userMoney,'商家提现申请提现',3);

            }else{

                M()->rollback();
                $error=array(
                    'status'=>false,
                    'error'=>'增加申请记录失败'
                );
                return $error;
            }

        }else{
            M()->rollback();
            $error=array(
                'status'=>false,
                'error'=>'申请异常'
            );
            return $error;
        }


        $re=array('status'=>true,'success'=>$status);





        return $re;
    }

    //申请提现-密码
    public function CheckApplyPassword(){

        $USER = session('WST_USER');
        

        $tempdata=M('users')->field('payPwd,loginSecret')->where(array('userId'=>$USER['userId']))->find();


        $PostPs = md5(I("payPwd").$tempdata['loginSecret']);
        $nowPs  = $tempdata['payPwd'];

        if($PostPs==$nowPs){
            $data=array('valid'=>true);

        }else{
            $data=array('valid'=>false);
        }


        return $data;
    }







    public function checkTime(){
        $USER = session('WST_USER');
        $set = M('agentset')->find();
        $tempdata = M('agentApply')->where(array('userId'=>$USER['userId']))->order('time DESC')->find();
        if($tempdata && $set['applyDay']!=0){
            $time = time();
            $ok_time = strtotime("+{$set['applyDay']} DAY",$tempdata['time']);

            $re['day'] = date("d",$ok_time-$time);



        }else{


            $re['day']=-1;
        }



        return $re;
    }


    //商家提现
    public function ApplyShopData(){

        $USER = session('WST_USER');
        $data=array();
        $tempdata = M('apply')->where(array('userId'=>$USER['userId'],'applyType'=>1))->select();

        foreach($tempdata as $key=>$value){

            $value['status']=$this->checkStatus($value['status']);
            $data[$key] = $value;
            $data[$key]['status']=$value['status'];
            $value['time']=date("Y-m-d",$value['time']);
            $data[$key] = $value;
            $data[$key]['time']=$value['time'];



        }





        return $data;

        
    }
    
    
    public function ApplyUserData(){
        $USER = session('WST_USER');
        $data=array();
        $tempdata = M('apply')->where(array('userId'=>$USER['userId'],'applyType'=>0))->select();

        foreach($tempdata as $key=>$value){

            $value['status']=$this->checkStatus($value['status']);
            $data[$key] = $value;
            $data[$key]['status']=$value['status'];
            $value['time']=date("Y-m-d",$value['time']);
            $data[$key] = $value;
            $data[$key]['time']=$value['time'];



        }
        
        return $data;
        
        
    }


    public function incomeShopData(){
        $USER = session('WST_USER');

        $shopId = (int)$USER['shopId'];
        $sql = "select i.id,i.orderId,i.money,i.time,i.proportion,i.pushShop,u.userName from oto_biz_income as i left JOIN oto_users as u on u.userId=i.userId where i.shopId=".$shopId;
        $res = M()->query($sql);

        return $res;
    }

    public function incomeCount()
    {
        $USER = session('WST_USER');

        $shopId = (int)$USER['shopId'];
        $res['pushShop'] = M('biz_income')->where(array('shopId'=>$shopId))->sum('pushShop');

        $res['applyOk'] = M('apply')->where(array('userId'=>$USER['userId'],'status'=>2,'applyType'=>1))->sum('applyPrice');
        $res['income'] = M('shops')->where(array('shopId'=>$shopId))->sum('bizMoney');
        if($res['applyOk']==null){
            $res['applyOk']=0;
        }
        return $res;
    }


    public function checkStatus($status)
    {

        switch ($status) {
            case 0:
                $status = '待处理';
                break;

            case 1:
                $status =  '处理中';
                break;
            case 2:
                $status =  '通过';
                break;

            case 3:
                $status =  '不通过';
                break;
            default:

                break;


        }

        return $status;
    }

    // 金额操作记录
    /**
     * 构造函数
     * @param $type 操作类型,1下单，2取消订单，3充值，4提现,5订单无效
     * @param $money 金额
     * @param $orderNo 订单编号或者充值ID
     * @param $IncDec 余额变动 0为减，1加
     * @param $userid 用户ID
     * @param $balance 余额
     * @param $remark 其它备注信息
     */
    private function moneyRecord($type = '', $money = 0, $orderNo = '', $IncDec = '', $userid = 0, $balance = 0,$remark='',$payWay=0) {
        $db = M ( 'money_record' );
        $data ['type'] = $type;
        $data ['money'] = $money;
        $data ['time'] = time ();
        $data ['ip'] = get_client_ip ();
        $data ['orderNo'] = $orderNo;
        $data ['IncDec'] = $IncDec;
        $data ['userid'] = $userid;
        $data ['balance'] = $balance;
        $data ['remark'] = $remark;
        $data ['payWay'] = $payWay;
        $res = $db->add ( $data );
        return $res;
    }


    public function WxCheckApplyPassword($userId,$password){

        $tempdata=M('users')->field('payPwd,loginSecret')->where(array('userId'=>$userId))->find();


        $PostPs = md5($password.$tempdata['loginSecret']);
        $nowPs  = $tempdata['payPwd'];

        if($PostPs==$nowPs){
            $data=true;

        }else{
            $data=false;
        }


        return $data;

    }
}